package com.cookie.meetproject.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cookie.framework.adapter.CommonAdapter;
import com.cookie.framework.adapter.CommonViewHolder;
import com.cookie.framework.base.BaseBackActivity;
import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.bmob.IMUser;
import com.cookie.framework.utils.CommonUtils;
import com.cookie.framework.view.LoadingView;
import com.cookie.meetproject.R;
import com.cookie.meetproject.adapter.AddFriendAdapter;
import com.cookie.meetproject.model.AddFriendModel;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class AddFriendActivity extends BaseBackActivity implements View.OnClickListener {

    //标题
    public static final int TYPE_TITLE = 0;
    //内容
    public static final int TYPE_CONTENT = 1;

    private LinearLayout llContact;
    private EditText etPhone;
    private ImageView ivSearch;
    private RecyclerView searchResultView;
    private CommonAdapter<AddFriendModel> addFriendAdapter;
    private List<AddFriendModel> mList = new ArrayList<>();
    private View includeEmptyView;
    private LoadingView loadingView;

    /**
     * 1.模拟用户数据
     * 2.根据条件查询
     * 3.推荐好友
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
        initView();
    }

    private void initView() {
        loadingView = new LoadingView(this);
        llContact = (LinearLayout) findViewById(R.id.ll_contact);
        etPhone = (EditText) findViewById(R.id.et_phone);
        ivSearch = (ImageView) findViewById(R.id.iv_search);
        searchResultView = (RecyclerView) findViewById(R.id.search_result_view);
        includeEmptyView = (View) findViewById(R.id.include_empty_view);
        llContact.setOnClickListener(this);
        ivSearch.setOnClickListener(this);

        searchResultView.setLayoutManager(new LinearLayoutManager(this));
        searchResultView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        //addFriendAdapter = new AddFriendAdapter(this, mList);
        addFriendAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnMoreBindDataListener<AddFriendModel>() {
            @Override
            public int getItemType(int position) {
                return mList.get(position).getType();
            }

            @Override
            public void onBindViewHolder(final AddFriendModel model, CommonViewHolder viewHolder, int type, int position) {
                if (type == TYPE_TITLE) {
                    viewHolder.setText(R.id.tv_title, model.getTitle());
                } else if (type == TYPE_CONTENT) {
                    viewHolder.setImageUrl(AddFriendActivity.this, R.id.iv_photo, model.getPhoto());
                    viewHolder.setImageResource(R.id.iv_sex, model.isSex() ? R.drawable.img_boy_icon
                            : R.drawable.img_girl_icon);
                    viewHolder.setText(R.id.tv_nickname, model.getNickName());
                    viewHolder.setText(R.id.tv_age, model.getAge() + "岁");
                    viewHolder.setText(R.id.tv_desc, model.getDesc());

                    //点击事件
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UserInfoActivity.startActivity(AddFriendActivity.this,model.getUserId());
                        }
                    });

                }
            }

            @Override
            public int getLayoutId(int type) {
                if (type == TYPE_TITLE) {
                    return R.layout.layout_search_title_item;
                } else if (type == TYPE_CONTENT) {
                    return R.layout.layout_search_user_item;
                }
                return 0;
            }
        });
        searchResultView.setAdapter(addFriendAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_contact:
                //跳转到从通讯录导入
                //处理权限
               /* if (checkPermissions(Manifest.permission.READ_CONTACTS)) {
                    LogUtils.i("点击了");
                    startActivity(new Intent(AddFriendActivity.this, ContactFriendActivity.class));
                } else {
                    requestPermission(new String[]{Manifest.permission.READ_CONTACTS});
                }*/
                startActivity(new Intent(AddFriendActivity.this, ContactFriendActivity.class));
                break;
            case R.id.iv_search:
                queryPhoneFriendUser();
                break;
        }
    }

    //通过电话号码查询
    private void queryPhoneFriendUser() {
        //1.获取电话号码
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, R.string.text_login_phone_null, Toast.LENGTH_SHORT).show();
            return;
        }
        //2.过滤自己
        String phoneNumber = BmobManger.getInstance().getUser().getMobilePhoneNumber();
        if (phone.equals(phoneNumber)) {
            loadingView.hide();
            Toast.makeText(this, "不能查询自己", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingView.show("正在查询中...");
        //3.查询
        BmobManger.getInstance().queryPhoneFriend(phone, new FindListener<IMUser>() {
            @Override
            public void done(List<IMUser> list, BmobException e) {
                if (e != null) {
                    loadingView.hide();
                    return;
                }
                if (CommonUtils.isEmpty(list)) {
                    IMUser imUser = list.get(0);
                    includeEmptyView.setVisibility(View.GONE);
                    searchResultView.setVisibility(View.VISIBLE);
                    mList.clear();
                    addTitle("查询结果");
                    addContent(imUser);
                    addFriendAdapter.notifyDataSetChanged();
                    //推荐
                    pushUser();
                    loadingView.hide();
                } else {
                    loadingView.hide();
                    //显示空数据
                    includeEmptyView.setVisibility(View.VISIBLE);
                    searchResultView.setVisibility(View.GONE);
                }
            }
        });
    }

    //推荐好友
    private void pushUser() {
        //查询所有的好友 取100个
        BmobManger.getInstance().queryAllUser(new FindListener<IMUser>() {
            @Override
            public void done(List<IMUser> list, BmobException e) {
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {
                        addTitle("推荐好友");
                        int num = (list.size() <= 100) ? list.size() : 100;
                        for (int i = 0; i < num; i++) {
                            //过滤自己
                            String phoneNumber = BmobManger.getInstance().getUser().getMobilePhoneNumber();
                            if (list.get(i).getMobilePhoneNumber().equals(phoneNumber)) {
                                //跳过本次循环
                                continue;
                            }
                            addContent(list.get(i));
                        }
                        addFriendAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    //添加头部
    private void addTitle(String title) {
        AddFriendModel model = new AddFriendModel();
        model.setType(AddFriendAdapter.TYPE_TITLE);
        model.setTitle(title);
        mList.add(model);
    }

    //添加内容
    private void addContent(IMUser imUser) {
        AddFriendModel model = new AddFriendModel();
        model.setType(AddFriendAdapter.TYPE_CONTENT);
        model.setUserId(imUser.getObjectId());
        model.setPhoto(imUser.getPhoto());
        model.setSex(imUser.isSex());
        model.setAge(imUser.getAge());
        model.setNickName(imUser.getNickName());
        model.setDesc(imUser.getDesc());
        mList.add(model);
    }
}
